In this project, you'll define and train a Generative Adverserial network of your own creation on a dataset of faces. Your goal is to get a generator network to generate new images of faces that look as realistic as possible!
The project will be broken down into a series of tasks from defining new architectures training adversarial networks. At the end of the notebook, you'll be able to visualize the results of your trained Generator to see how it performs; your generated samples should look like fairly realistic faces with small amounts of noise.
You'll be using the CelebFaces Attributes Dataset (CelebA) to train your adversarial networks.
This dataset has higher resolution images than datasets you have previously worked with (like MNIST or SVHN) you've been working with, and so, you should prepare to define deeper networks and train them for a longer time to get good results. It is suggested that you utilize a GPU for training.
Since the project's main focus is on building the GANs, we've done some of the pre-processing for you. Each of the CelebA images has been cropped to remove parts of the image that don't include a face, then resized down to 64x64x3 NumPy images. Some sample data is show below.

If you are working locally, you can download this data by clicking here
This is a zip file that you'll need to extract in the home directory of this notebook for further loading and processing. After extracting the data, you should be left with a directory of data processed-celeba-small/.
#run this once to unzip the file
#!unzip processed-celeba-small.zip
from glob import glob
from typing import Tuple, Callable, Dict
import matplotlib.pyplot as plt
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Module
from PIL import Image
from torch.utils.data import DataLoader, Dataset
from torchvision.transforms import Compose, ToTensor, Resize, Normalize
from torchvision import transforms
import tests
import os
data_dir = 'processed_celeba_small/celeba/'
The CelebA dataset contains over 200,000 celebrity images with annotations. Since you're going to be generating faces, you won't need the annotations, you'll only need the images. Note that these are color images with 3 color channels (RGB)#RGB_Images) each.
Since the project's main focus is on building the GANs, we've done some of the pre-processing for you. Each of the CelebA images has been cropped to remove parts of the image that don't include a face, then resized down to 64x64x3 NumPy images. This pre-processed dataset is a smaller subset of the very large CelebA dataset and contains roughly 30,000 images.
Your first task consists in building the dataloader. To do so, you need to do the following:
The get_transforms function should output a torchvision.transforms.Compose of different transformations. You have two constraints:
def get_transforms(size: Tuple[int, int]) -> Callable:
""" Transforms to apply to the image."""
# TODO: edit this function by appening transforms to the below list
transforms = [ToTensor(), Resize(size), Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]
return Compose(transforms)
The DatasetDirectory class is a torch Dataset that reads from the above data directory. The __getitem__ method should output a transformed tensor and the __len__ method should output the number of files in our dataset. You can look at this custom dataset for ideas.
class DatasetDirectory(Dataset):
"""
A custom dataset class that loads images from folder.
args:
- directory: location of the images
- transform: transform function to apply to the images
- extension: file format
"""
def __init__(self, directory: str, transforms: Callable = None, extension: str = '.jpg'):
# TODO: implement the init method
self.directory = directory
self.transforms = transforms
self.extension = '.jpg'
self.d_list = glob(directory + "*" + extension)
def __len__(self) -> int:
""" returns the number of items in the dataset """
# TODO: return the number of elements in the dataset
return len(self.d_list)
def __getitem__(self, index: int) -> torch.Tensor:
""" load an image and apply transformation """
# TODO: return the index-element of the dataset
img_path = self.d_list[index]
im = Image.open(img_path)
im = self.transforms(im)
return im
"""
DO NOT MODIFY ANYTHING IN THIS CELL
"""
# run this cell to verify your dataset implementation
dataset = DatasetDirectory(data_dir, get_transforms((64, 64)))
tests.check_dataset_outputs(dataset)
The functions below will help you visualize images from the dataset.
"""
DO NOT MODIFY ANYTHING IN THIS CELL
"""
def denormalize(images):
"""Transform images from [-1.0, 1.0] to [0, 255] and cast them to uint8."""
return ((images + 1.) / 2. * 255).astype(np.uint8)
# plot the images in the batch, along with the corresponding labels
fig = plt.figure(figsize=(20, 4))
plot_size=20
for idx in np.arange(plot_size):
ax = fig.add_subplot(2, int(plot_size/2), idx+1, xticks=[], yticks=[])
img = dataset[idx].numpy()
img = np.transpose(img, (1, 2, 0))
img = denormalize(img)
ax.imshow(img)
As you know, a GAN is comprised of two adversarial networks, a discriminator and a generator. Now that we have a working data pipeline, we need to implement the discriminator and the generator.
Feel free to implement any additional class or function.
The discriminator's job is to score real and fake images. You have two constraints here:
Feel free to get inspiration from the different architectures we talked about in the course, such as DCGAN, WGAN-GP or DRAGAN.
Conv2d layers with the correct hyperparameters or Pooling layers.conv_dim = 16
# custom weights initialization called on discriminator and generator
def costum_weights(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
nn.init.normal_(m.weight.data, 0.0, 0.02)
elif classname.find('BatchNorm') != -1:
nn.init.normal_(m.weight.data, 1.0, 0.02)
nn.init.constant_(m.bias.data, 0)
def conv_block(in_channels, out_channels,kernel_size=4, stride=2, padding=1, b_n=True):
layers = []
block = nn.Conv2d(in_channels, out_channels, kernel_size, stride, padding, bias=False) # no bias bc of b_n mean=0
layers.append(block)
if b_n:
layers.append(nn.BatchNorm2d(out_channels))
return nn.Sequential(*layers)
conv_dim = 64
class Discriminator(Module):
def __init__(self):
super(Discriminator, self).__init__()
# TODO: instantiate the different layers
self.conv_dim = conv_dim
#3x64x64
self.conv1 = conv_block(3, conv_dim,4, b_n=False) # default kernel_size = 4
#32x32x32 - conv_dim = 32
self.conv2 = conv_block(conv_dim, conv_dim*2)
#64x16x16
self.conv3 = conv_block(conv_dim*2, conv_dim*4)
#128x8x8
self.conv4 = conv_block(conv_dim*4, conv_dim*8)
#256x4x4
self.conv5 = conv_block(conv_dim*8, 1, 4, 1, 0, b_n=False)
#1x1x1
def forward(self, x: torch.Tensor) -> torch.Tensor:
# TODO: implement the forward method
#print(x.size())
x = F.leaky_relu(self.conv1(x), 0.2) # slope of leaky relu set to 0.2
x = F.leaky_relu(self.conv2(x), 0.2)
x = F.leaky_relu(self.conv3(x), 0.2)
x = F.leaky_relu(self.conv4(x), 0.2)
x = torch.sigmoid(self.conv5(x))
return x
discriminator = Discriminator()
# Apply the weights_init function to randomly initialize all weights
# to mean=0, stdev=0.2.
discriminator.apply(costum_weights)
# Print the model
#print(discriminator)
"""
DO NOT MODIFY ANYTHING IN THIS CELL
"""
# run this cell to check your discriminator implementation
### line modified outcommented: discriminator = Discriminator()
tests.check_discriminator(discriminator)
The generator's job creates the "fake images" and learns the dataset distribution. You have three constraints here:
[batch_size, latent_dimension, 1, 1]Feel free to get inspiration from the different architectures we talked about in the course, such as DCGAN, WGAN-GP or DRAGAN.
ConvTranspose2d layers# Helper function for orderly building of layer-blocks
def deconv_block(in_channels, out_channels,kernel_size=4, stride=2, padding=1, b_n=True):
layers = []
trans_block = nn.ConvTranspose2d(in_channels, out_channels, kernel_size, stride, padding, bias=False) # no bias bc of b_n mean=0
layers.append(trans_block)
if b_n:
layers.append(nn.BatchNorm2d(out_channels))
return nn.Sequential(*layers)
class Generator(Module):
def __init__(self, latent_dim: int):
super(Generator, self).__init__()
# TODO: instantiate the different layers
self.conv_dim = 64
self.deconv1 = deconv_block(latent_dim, conv_dim*8, 4, 1, 0)
#256x4x4
self.deconv2 = deconv_block(conv_dim*8, conv_dim*4)
#128x8x8
self.deconv3 = deconv_block(conv_dim*4, conv_dim*2)
#64x16x16
self.deconv4 = deconv_block(conv_dim*2, conv_dim)
#32x32x32
self.deconv5 = deconv_block(conv_dim,3, b_n=False) # no batchnorm at generator output
#3x64x64
def forward(self, x: torch.Tensor) -> torch.Tensor:
# Implement the forward method
x = F.relu(self.deconv1(x))
x = F.relu(self.deconv2(x))
x = F.relu(self.deconv3(x))
x = F.relu(self.deconv4(x))
x = torch.tanh(self.deconv5(x))
return x
latent_dim = 128
generator = Generator(latent_dim)
# Apply the weights_init function to randomly initialize all weights
# to mean=0, stdev=0.2.
generator.apply(costum_weights)
# Print the model
print(generator)
"""
DO NOT MODIFY ANYTHING IN THIS CELL
"""
# run this cell to verify your generator implementation
latent_dim = 128
## outcommented: generator = Generator(latent_dim)
tests.check_generator(generator, latent_dim)
In the following section, we create the optimizers for the generator and discriminator. You may want to experiment with different optimizers, learning rates and other hyperparameters as they tend to impact the output quality.
import torch.optim as optim
# parameters
lr = 0.003
beta1=0.5
beta2=0.999 # default value for computer-vision task
def create_optimizers(generator: Module, discriminator: Module):
""" This function should return the optimizers of the generator and the discriminator """
# Implement the generator and discriminator optimizers
g_optimizer = optim.Adam(generator.parameters(), lr, [beta1, beta2])
d_optimizer = optim.Adam(discriminator.parameters(), lr, [beta1, beta2])
return g_optimizer, d_optimizer
In this section, we are going to implement the loss function for the generator and the discriminator. You can and should experiment with different loss function.
Some tips:
The generator's goal is to get the discriminator to think its generated images (= "fake" images) are real.
# BCELoss is used as Sigmoid is already manually applied on discriminator output
def generator_loss(fake_logits, smooth=False):
""" Generator loss, takes the fake scores as inputs. """
# Implement the generator loss
## Real losses
batch_size = fake_logits.size(0)
if smooth:
labels = torch.ones(batch_size)*0.9
else:
labels = torch.ones(batch_size)
labels = labels.to(device)
criterion = nn.BCEWithLogitsLoss()
loss = criterion(fake_logits.squeeze(), labels)
return loss
We want the discriminator to give high scores to real images and low scores to fake ones and the discriminator loss should reflect that.
def discriminator_loss(real_logits, fake_logits, smooth=False):
""" Discriminator loss, takes the fake and real logits as inputs. """
# Implement the discriminator loss
## Real losses
batch_size = real_logits.size(0)
if smooth:
labels = torch.ones(batch_size)*0.9
else:
labels = torch.ones(batch_size)
labels = labels.to(device)
criterion = nn.BCELoss()
real_loss = criterion(real_logits.squeeze(), labels)
## Fake losses
batch_size_f = fake_logits.size(0)
labels_f = torch.zeros(batch_size_f).to(device)
fake_loss = criterion(fake_logits.squeeze(), labels_f)
return real_loss + fake_loss
In the course, we discussed the importance of gradient penalty in training certain types of Gans. Implementing this function is not required and depends on some of the design decision you made (discriminator architecture, loss functions).
# Batch-normalizations are applied which is why gradient penalty was not
Training will involve alternating between training the discriminator and the generator. You'll use your functions real_loss and fake_loss to help you calculate the discriminator losses.
Each function should do the following:
def generator_step(batch_size: int, latent_dim: int) -> Dict:
""" One training step of the generator. """
# Implement the generator step (foward pass, loss calculation and backward pass)
g_optimizer.zero_grad()
# Feeding fake images
fake_images = generator((torch.randn(batch_size, latent_dim, 1, 1).float().to(device)))
D_fake = discriminator(fake_images)
# Losses
g_loss = generator_loss(D_fake, smooth=False)
# Backpropagation step
g_loss.backward()
g_optimizer.step()
return {'loss': g_loss}
def discriminator_step(batch_size: int, latent_dim: int, real_images: torch.Tensor) -> Dict:
""" One training step of the discriminator. """
# Implement the discriminator step (foward pass, loss calculation and backward pass)
d_optimizer.zero_grad()
batch_size = real_images.size(0)
# Feeding real images
D_real = discriminator(real_images)
# Feeding fake images
fake_images = generator((torch.randn(batch_size, latent_dim, 1, 1).float().to(device)))
D_fake = discriminator(fake_images)
# Losses
d_loss = discriminator_loss(D_real, D_fake, smooth=True) # one-sided label smoothing, only discriminator
# Backpropagation Step
d_loss.backward()
d_optimizer.step()
return {'loss': d_loss} # no gradient penalty because of batch_normalizations
You don't have to implement anything here but you can experiment with different hyperparameters.
from datetime import datetime
# you can experiment with different dimensions of latent spaces
latent_dim = 100
# update to cpu if you do not have access to a gpu
device = 'cuda' if torch.cuda.is_available() else 'cpu'
# number of epochs to train your model
n_epochs = 12
# number of images in each batch
batch_size = 32
"""
DO NOT MODIFY ANYTHING IN THIS CELL
"""
print_every = 50
# Create optimizers for the discriminator D and generator G
generator = Generator(latent_dim).to(device)
discriminator = Discriminator().to(device)
g_optimizer, d_optimizer = create_optimizers(generator, discriminator)
dataloader = DataLoader(dataset,
batch_size=64,
shuffle=True,
num_workers=4,
drop_last=True,
pin_memory=False)
"""
DO NOT MODIFY ANYTHING IN THIS CELL
"""
def display(fixed_latent_vector: torch.Tensor):
""" helper function to display images during training """
fig = plt.figure(figsize=(14, 4))
plot_size = 16
for idx in np.arange(plot_size):
ax = fig.add_subplot(2, int(plot_size/2), idx+1, xticks=[], yticks=[])
img = fixed_latent_vector[idx, ...].detach().cpu().numpy()
img = np.transpose(img, (1, 2, 0))
img = denormalize(img)
ax.imshow(img)
plt.show()
You should experiment with different training strategies. For example:
Implement with your training strategy below.
fixed_latent_vector = torch.randn(16, latent_dim, 1, 1).float().cuda()
losses = []
for epoch in range(n_epochs):
for batch_i, real_images in enumerate(dataloader):
real_images = real_images.to(device)
####################################
## Discriminator Training
d_loss = discriminator_step(batch_size, latent_dim, real_images)
## Generator Training
g_loss = generator_step(batch_size, latent_dim)
####################################
if batch_i % print_every == 0:
# append discriminator loss and generator loss
d = d_loss['loss'].item()
g = g_loss['loss'].item()
losses.append((d, g))
# print discriminator and generator loss
time = str(datetime.now()).split('.')[0]
print(f'{time} | Epoch [{epoch+1}/{n_epochs}] | Batch {batch_i}/{len(dataloader)} | d_loss: {d:.4f} | g_loss: {g:.4f}')
# display images during training
generator.eval()
generated_images = generator(fixed_latent_vector)
display(generated_images)
generator.train()
Plot the training losses for the generator and discriminator.
"""
DO NOT MODIFY ANYTHING IN THIS CELL
"""
fig, ax = plt.subplots()
losses = np.array(losses)
plt.plot(losses.T[0], label='Discriminator', alpha=0.5)
plt.plot(losses.T[1], label='Generator', alpha=0.5)
plt.title("Training Losses")
plt.legend()
When you answer this question, consider the following factors:
Answer: Overall the model is geared towards generating realistic images, limitations are that the dataset as of now is trained in an imbalanced way, in essence this means that many features are not only overrepresented in the dataset, as e.g. caucasian ethnicity, but also that certain features are recognized better by the model, and therefore easier trained than others, these e.g. include lipstick or long hair. To overcome this, features which are harder to be trained, like nuances in skin color or smaller facial features like eye shape, could be identified and oversampled, additionally more abstract and advanced data augmentation techniques can help the filters to extract more useful information from the enlargened dataset. Batch normalizations where applied as the standard, which can be switched to gradient penalty in trials, also Wasserstein Loss is a new approach that may lead to better optimizations. Artifacts remaining from partial generation of glasses or earings can be approached by adapting key-components from ProgressiveGAN and StyleGAN, like InterFaceGAN for Semantic Face Editing.
When submitting this project, make sure to run all the cells before saving the notebook. Save the notebook file as "dlnd_face_generation.ipynb".
Submit the notebook using the SUBMIT button in the bottom right corner of the Project Workspace.